package com.tgy.leetcode;

/**
 * https://leetcode-cn.com/problems/search-in-rotated-sorted-array/
 */
public class _33_搜索旋转排序数组 {

    public static int search(int[] nums, int target) {

        if (nums == null || nums.length == 0) {
            return -1;
        }

        int len = nums.length;

        if (len == 1) {

            return nums[0] == target? 0:-1;
        }

        int left = 0, right = len - 1, mid;

        while (left <= right) {

            mid = left + ((right - left) >> 1);

            if (target == nums[mid]) {

                return mid;
            }

            if (nums[mid] < nums[right]) {

                if (target > nums[mid] && target <= nums[right]) {

                    left = mid+1;
                }else {

                    right = mid - 1;
                }
            }else {

                if (target >= nums[left] && target < nums[mid]) {

                    right = mid - 1;
                }else {

                    left = mid + 1;
                }
            }

        }

        return -1;
    }

    public static void main(String[] args) {

        int[] nums = {4,5,6,7,0,1,2};
        System.out.println(search(nums, 6));
    }
}
